package cn.hfatec.shms.base;

import cn.hfatec.shms.exception.NotAuthException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException;
import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

/**
 *
 *
 *
 * @author: panwb
 *
 * Date: 2015/11/17
 * Time: 9:28
 */
@ControllerAdvice
public class ShmsExceptionHandler extends DefaultHandlerExceptionResolver {

    private Logger logger = LoggerFactory.getLogger(ShmsExceptionHandler.class);

    /**
     *
     * 统一异常处理
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(value = {Exception.class, ServletException.class})
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public String handlerException(Exception ex) {
        logger.error("内部异常错误", ex);
        if(ex instanceof NotAuthException) {
            return "login";
        }
        return "exception/500";
    }

    /**
     *
     * 404异常捕获处理
     *
     * @param ex
     * @param request
     * @return
     */
    @ExceptionHandler(value = {NoSuchRequestHandlingMethodException.class, NoHandlerFoundException.class})
    @ResponseStatus(value = HttpStatus.NOT_FOUND)
    public String handler404(Exception ex, HttpServletRequest request) {
        logger.error("{},404找不到请求", request.getRequestURL().toString(), ex);
        request.setAttribute("message",
                request.getRequestURL().toString() + "request not found");
        return "exception/404";
    }
}
